from rest_framework.decorators import api_view
from rest_framework.response import Response # django使用的是JsonResponse或HttpResponse，而drf直接封装好了，就是Response
from rest_framework import status
from course.models import Course
from course.serializers import CourseSerializer

# 问ai这个地方为什么会报警告

from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.permissions import IsAuthenticated

from rest_framework.views import APIView

from rest_framework import viewsets


# 学习到了带token能不能访问我之前写的这些接口，教程也看token那里
"""一、函数式编程 Function Based View"""
@csrf_exempt
@api_view(["GET", "POST"])
# @permission_classes([AllowAny])
# @permission_classes([IsAuthenticated])
def course_list(request):
    """
    获取所有课程信息或新增一个课程
    :param request:
    :return:
    """
    if request.method == "GET":
        s = CourseSerializer(instance=Course.objects.all(), many=True) # 序列化多个对象，所以需要many=True
        # 序列化后的数据可以通过s.data获得
        return Response(data=s.data, status=status.HTTP_200_OK)
    elif request.method == "POST":
        s = CourseSerializer(data=request.data, partial=True) # 反序列化, partial=True表示部分更新
        if s.is_valid():
            s.save(teacher=request.user) # 讲师是只读属性
            return Response(data=s.data, status=status.HTTP_201_CREATED)
        return Response(s.erros, status=status.HTTP_400_BAD_REQUEST)

@api_view(["GET", "PUT", "DELETE"])
@csrf_exempt
@permission_classes([AllowAny])
def course_detail(request, pk): # 通过url传递pk
    """
    获取、更新、删除一个课程
    :param request:
    :param pk:
    :return:
    """
    try:
        course = Course.objects.get(pk=pk)
    except Course.DoesNotExist:
        return Response(data={"msg": "没有此课程信息"}, status=status.HTTP_404_NOT_FOUND)
    else:
        if request.method == "GET":
            s = CourseSerializer(instance=course) # 序列化一个对象不需要many=True
            return Response(data=s.data, status=status.HTTP_200_OK)

        elif request.method == "PUT": # PUT方法表示更新，部分写法和POST方法类似
            s = CourseSerializer(instance=course, data=request.data) #instance是指要序列化哪个实例，data表示数据哪里来的
            # 表示把data的数据，反序列化之后，保存或者更新到cuorse对象里
            if s.is_valid():
                s.save() # 不需要teacher字段
                return Response(s.data, status=status.HTTP_200_OK)

        elif request.method == "DELETE":
            course.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)